<?php

namespace app\repository\common;

use app\models\common\OauthClientsModel;

class OauthClients
{
    protected $model;

    function __construct()
    {
        $this->model = new OauthClientsModel();
    }

    /**
     * 根据Id获取详细信息
     * @param $id
     * @return array
     * @date 2020-08-10 15:04
     */
    public function getInfoById($id)
    {
        return $this->model->getInfoById($id);
    }

    /**
     * 根据token获取信息
     * @param $token
     * @return array
     * @date 2020-08-10 16:40
     */
    public function getInfoByToken($token)
    {
        return $this->model->getInfoByToken($token);
    }

    /**
     * 检查客户端是否有对应的权限
     * @param $urlPath
     * @param array $resourceList
     * @return bool
     * @date 2020-08-14 14:04
     */
    public function checkClientHadPower($urlPath, $requestMethod, array $resourceList = [])
    {
        if (!$resourceList) {
            return false;
        }
        $urlPath = str_replace('api', '', $urlPath);
        $urlPath = trim($urlPath, '/');
        $urlPathArr = explode('/', $urlPath);
        $requestMethod = strtolower($requestMethod);
        foreach ($resourceList as $v) {
            $v['path'] = trim($v['path'], '/');
            $pathArr = explode('/', $v['path']);
            if ($v['request_method'] !== $requestMethod) {
                continue;
            }
            if (count($urlPathArr) != count($pathArr)) {
                continue;
            }
            foreach ($pathArr as $pk => $pv) {
                if (!isset($urlPathArr[$pk])) {
                    continue;
                }
                if ($pv != '{data}' && $pv != $urlPathArr[$pk]) {
                    continue;
                }
            }
            return true;
        }
        return false;
    }
}
